<template>
  <div class="logs">
    <div class="page-header">
      <h1>日志查看</h1>
      <el-button type="success" @click="handleExport">
        <el-icon><Download /></el-icon>
        导出日志
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filters">
      <el-input
        v-model="searchQuery"
        placeholder="搜索日志内容"
        style="width: 300px; margin-right: 10px;"
        @input="handleSearch"
      />
      <el-select v-model="levelFilter" placeholder="日志级别" style="width: 150px; margin-right: 10px;" @change="handleSearch">
        <el-option label="全部" value="" />
        <el-option label="INFO" value="INFO" />
        <el-option label="WARNING" value="WARNING" />
        <el-option label="ERROR" value="ERROR" />
        <el-option label="DEBUG" value="DEBUG" />
      </el-select>
      <el-select v-model="moduleFilter" placeholder="模块筛选" style="width: 150px; margin-right: 10px;" @change="handleSearch">
        <el-option label="全部" value="" />
        <el-option label="认证" value="auth" />
        <el-option label="用户" value="users" />
        <el-option label="考试" value="exams" />
        <el-option label="成绩" value="scores" />
        <el-option label="系统" value="system" />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        style="width: 350px; margin-right: 10px;"
        @change="handleSearch"
      />
    </div>

    <!-- 日志统计 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" size="32" color="#409EFF">
              <Document />
            </el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ logStats.total || 0 }}</div>
              <div class="stat-label">总日志数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" size="32" color="#F56C6C">
              <Warning />
            </el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ logStats.errors || 0 }}</div>
              <div class="stat-label">错误日志</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" size="32" color="#E6A23C">
              <WarningFilled />
            </el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ logStats.warnings || 0 }}</div>
              <div class="stat-label">警告日志</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" size="32" color="#67C23A">
              <Check />
            </el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ logStats.today || 0 }}</div>
              <div class="stat-label">今日日志</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 日志列表 -->
    <el-table :data="logs" style="width: 100%" v-loading="loading">
      <el-table-column prop="timestamp" label="时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.timestamp) }}
        </template>
      </el-table-column>
      <el-table-column prop="level" label="级别" width="100">
        <template #default="{ row }">
          <el-tag :type="getLevelType(row.level)">
            {{ row.level }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="module" label="模块" width="120">
        <template #default="{ row }">
          <el-tag :type="getModuleType(row.module)" size="small">
            {{ getModuleText(row.module) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="user" label="用户" width="120">
        <template #default="{ row }">
          {{ row.user || '系统' }}
        </template>
      </el-table-column>
      <el-table-column prop="action" label="操作" width="150" />
      <el-table-column prop="message" label="日志信息" show-overflow-tooltip />
      <el-table-column prop="ip_address" label="IP地址" width="120" />
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="日志详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="时间">{{ formatDateTime(selectedLog.timestamp) }}</el-descriptions-item>
        <el-descriptions-item label="级别">
          <el-tag :type="getLevelType(selectedLog.level)">
            {{ selectedLog.level }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="模块">
          <el-tag :type="getModuleType(selectedLog.module)" size="small">
            {{ getModuleText(selectedLog.module) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="用户">{{ selectedLog.user || '系统' }}</el-descriptions-item>
        <el-descriptions-item label="操作">{{ selectedLog.action }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ selectedLog.ip_address }}</el-descriptions-item>
        <el-descriptions-item label="用户代理" :span="2">{{ selectedLog.user_agent || '未知' }}</el-descriptions-item>
        <el-descriptions-item label="日志信息" :span="2">{{ selectedLog.message }}</el-descriptions-item>
        <el-descriptions-item label="详细信息" :span="2">
          <pre>{{ formatJson(selectedLog.details) }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import api from '../api';
import { ElMessage } from 'element-plus';
import { Download, Document, Warning, WarningFilled, Check } from '@element-plus/icons-vue';

const logs = ref([]);
const loading = ref(false);
const showDetailDialog = ref(false);
const selectedLog = ref({});
const logStats = ref({});

// 分页和筛选
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const searchQuery = ref('');
const levelFilter = ref('');
const moduleFilter = ref('');
const dateRange = ref([]);

const formatDateTime = (datetime) => {
  return new Date(datetime).toLocaleString('zh-CN');
};

const formatJson = (json) => {
  if (!json) return '无';
  try {
    return JSON.stringify(JSON.parse(json), null, 2);
  } catch {
    return json;
  }
};

const getLevelType = (level) => {
  const levelMap = {
    'INFO': 'info',
    'WARNING': 'warning',
    'ERROR': 'danger',
    'DEBUG': 'success'
  };
  return levelMap[level] || 'info';
};

const getModuleType = (module) => {
  const moduleMap = {
    'auth': 'danger',
    'users': 'warning',
    'exams': 'success',
    'scores': 'primary',
    'system': 'info'
  };
  return moduleMap[module] || 'info';
};

const getModuleText = (module) => {
  const moduleMap = {
    'auth': '认证',
    'users': '用户',
    'exams': '考试',
    'scores': '成绩',
    'system': '系统'
  };
  return moduleMap[module] || '未知';
};

const loadLogs = async () => {
  loading.value = true;
  try {
    const params = {};
    
    // 只添加非空的参数
    if (searchQuery.value) {
      params.search = searchQuery.value;
    }
    if (levelFilter.value) {
      params.level = levelFilter.value;
    }
    if (moduleFilter.value) {
      params.module = moduleFilter.value;
    }
    if (dateRange.value && dateRange.value.length === 2) {
      params.start_date = dateRange.value[0];
      params.end_date = dateRange.value[1];
    }
    
    // 分页参数
    params.skip = (currentPage.value - 1) * pageSize.value;
    params.limit = pageSize.value;
    
    const response = await api.logs.getLogs(params);
    logs.value = response.data.items || response.data;
    total.value = response.data.total || (response.data.items ? response.data.items.length : 0);
  } catch (error) {
    console.error('加载日志列表失败:', error);
    ElMessage.error('加载日志列表失败');
  } finally {
    loading.value = false;
  }
};

const loadLogStats = async () => {
  try {
    const response = await api.logs.getLogStats();
    logStats.value = response.data;
  } catch (error) {
    console.error('加载日志统计失败:', error);
  }
};

const handleSearch = () => {
  currentPage.value = 1;
  loadLogs();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  loadLogs();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  loadLogs();
};

const handleViewDetail = (log) => {
  selectedLog.value = log;
  showDetailDialog.value = true;
};

const handleExport = async () => {
  try {
    const params = {};
    
    if (searchQuery.value) {
      params.search = searchQuery.value;
    }
    if (levelFilter.value) {
      params.level = levelFilter.value;
    }
    if (moduleFilter.value) {
      params.module = moduleFilter.value;
    }
    if (dateRange.value && dateRange.value.length === 2) {
      params.start_date = dateRange.value[0];
      params.end_date = dateRange.value[1];
    }
    
    const response = await api.logs.exportLogs(params);
    
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `logs_${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('日志导出成功');
  } catch (error) {
    console.error('导出日志失败:', error);
    ElMessage.error('导出日志失败');
  }
};

onMounted(() => {
  loadLogs();
  loadLogStats();
});
</script>

<style scoped>
.logs {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.filters {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  margin-right: 16px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

pre {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  margin: 0;
}
</style>